<template>
  <div class="loan">
    <assets-head :title="$t('助力贷')">
      <div class="right">
        <img src="../../assets/image/loan/rule.png" alt="rule-img" class="w-50 h-50 mr-20"
          @click="$router.push('/loanRule')" />
        <img src="../../assets/image/loan/history.png" alt="exchange-img" class="w-50 h-50"
          @click="$router.push('/loanHistory')" />
      </div>
    </assets-head>

    <!--   container -->
    <div class="container px-32">
      <!--      title-->
      <div class="py-30">
        <span style="color: #E35461;">{{ this.$t('经过平台审核，您可向平台申请一笔借款！') }}</span>
      </div>
      <!--    list  -->
      <div class="loanList">
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $t('期望借款金额') }}</span>
          </div>
          <div class="flex align-center">
            <input class="font-600 textColor border-none text-right mr-14 mainBackground w-280" v-model="loanAmount"  @input="inputAmunt" />
            <!--            <span class="mr-14 font-600 textColor">{{ loanData.maxQuota || 0 }}</span>-->
            <span class="font-600 textColor">USDT</span>
          </div>
        </div>
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $t('还款周期') }}</span>
          </div>
          <div class="flex align-center">
            <!--            <div class="font-600 textColor relative">-->
            <div class="font-600 mr-14 textColor relative" @click="isSelectDay = !isSelectDay">
              <span>{{ loanData.term }} {{ $t('Day') }}</span>
              <!--              <div class="selectDay"  v-show="isSelectDay">-->
              <!--                <div class="mb-20 border-b-white" v-for="(s,index) in selectDayList" :key="index"  @click="selectDay(s)">-->
              <!--                  <span>{{s}}</span>-->
              <!--                </div>-->
              <!--              </div>-->
            </div>
            <div class="w-24 h-24">
              <img src="../../assets/image/loan/right.png" alt="right-img" class="w-full">
            </div>
          </div>
        </div>
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $i18n.locale==='en' ? 'Daily Interest Rate' :$t('日利率')}}</span>
          </div>
          <div class="flex align-center">
            <span class="font-600 textColor">{{ loanData.dailyRate * 1 * 100 || 0 }}%</span>
          </div>
        </div>
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $t('还款方式') }}</span>
          </div>
          <div class="flex align-center">
            <span class="font-600 textColor text-right">{{ $t('到期一次还款') }}</span>
          </div>
        </div>
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $t('利息') }}</span>
          </div>
          <div class="flex align-center">
            <!--            借款金额*日利率*借款天数-->
            <!--            <span class="font-600 textColor">-->
            <!--              {{ $bigDecimal.multiply(+loanData.maxQuota, +loanData.dailyRate) * +this.loanData.term || 0 }} USDT-->
            <!--            </span>-->
            <span class="font-600 textColor">{{getInterest()}} USDT</span>
          </div>
        </div>
        <div class="flex justify-between py-30 border-b-grey">
          <div>
            <span class="grayText">{{ $t('放款机构') }}</span>
          </div>
          <div class="flex align-center">
            <span class="font-600 textColor">{{ loanData.lendingName }}</span>
          </div>
        </div>
      </div>
      <!--      上传区域-->
      <div class="uploadImg">
        <div class="mb-40 textColor">
          <span>{{ $t('信用放款(请确保图片清晰可见)') }}</span>
        </div>
        <div class="upload">
          <div class="flex mt-33 mb-80 justify-between">
            <div class="flex-1 flex flex-col text-center justify-center items-center">
              <div class="upload-wrap">
                <!--                    <img src="@/assets/image/kyc/0.png" alt="" class="w-full"-->
                <!--                         v-if="[1, 2].includes(status) && frontFile.length === 0" />-->
                <van-uploader v-model="frontFile" :max-count="1" :after-read="(file)=>afterRead(file,'frontFile')" :before-read="beforeRead"/>
              </div>
              <div class="mt-32 font-26 h-20" style="color:#868D9A;">{{ $t('证件正面') }}</div>
            </div>
            <div class="flex-1 flex flex-col text-center justify-center items-center">
              <div class="upload-wrap">
                <!--                    <img src="@/assets/image/kyc/1.png" alt="" class="w-full"-->
                <!--                         v-if="[1, 2].includes(status) && reverseFile.length === 0" />-->
                <van-uploader v-model="reverseFile" :max-count="1" :after-read="(file)=>afterRead(file,'reverseFile')" :before-read="beforeRead"/>
              </div>
              <div class="mt-32 font-26 h-20" style="color:#868D9A;">{{ $t('证件反面') }}</div>
            </div>
          </div>
          <div class="flex mt-33 mb-80 justify-between">
            <div class="flex-1 flex flex-col text-center justify-center items-center">
              <div class="upload-wrap">
                <!--                    <img src="@/assets/image/kyc/2.png" alt="" class="w-full"-->
                <!--                         v-if="[1, 2].includes(status) && fileList.length === 0" />-->
                <van-uploader v-model="fileList" :max-count="1" :after-read="(file)=>afterRead(file,'fileList')" :before-read="beforeRead"/>
              </div>
              <div class="mt-32 font-26 h-20" style="color:#868D9A;">{{ $t('手持证件照') }}</div>
            </div>
            <div class="flex-1 flex flex-col text-center justify-center items-center">
              <div class="upload-wrap">
                <img src="@/assets/image/loan/handId.png" alt="" class="w-full" />
              </div>
              <div class="mt-32 font-26 h-20" style="color:#868D9A;">{{ $t('拍摄示例') }}</div>
            </div>
          </div>
        </div>
      </div>

      <!--      确认按钮-->
      <div class="confirmBtn btnMain w-full py-30 text-center text-white font-400 font-32" @click="submit()">
        <span>{{ $t('确定') }}</span>
      </div>
    </div>
    <van-popup v-model="isSelectDay" position="bottom" :round="true">
      <ul class="bg-white">
        <li v-for="(day, index) in loanDeployList" class="text-center py-30" :key="index" @click="selectDay(day)">
          <span>{{ day.term }}</span>
        </li>
      </ul>
    </van-popup>
  </div>
</template>

<script>
import AssetsHead from "@/components/assets-head/index.vue";
import { Popup, Uploader } from "vant";
import { _uploadImage, _getLoan, _loanApply } from "@/API/fund.api";
import {debounce} from "@/utils/utis";
import { mapGetters } from "vuex";

export default {
  name: "loanIndex",
  components: {
    AssetsHead,
    [Uploader.name]: Uploader,
    [Popup.name]: Popup,
  },
  computed: {
    ...mapGetters('user', ['userInfo'])
  },
  methods: {
    beforeRead(file){
      const imageTypeList = ['image/jpeg','image/jpg','image/png']
      if (!imageTypeList.includes(file.type)) {
        this.$toast(this.$t('上传图片只能是JPG、JPEG、PNG格式!'));
        return false;
      }
      return true;
    },
    getLoan() {
      _getLoan().then(data => {
        this.loanDeployList = data.data;
        this.loanDeployList.sort((a, b) => {
          return +a.term - +b.term
        })
        this.loanData = this.loanDeployList[0]
        this.loanAmount = this.loanData.minQuota
      })
    },
    submit() {
      if(this.loanAmount<=0){
        this.$toast(this.$t('请输入金额'));
        return
      }
      
      if (!this.frontFile.length || !this.reverseFile.length || !this.fileList.length) {
        this.$toast(this.$t('请上传完整证件信息'))
        return
      }
      if (!this.isLoad1) {
        this.$toast(this.$t('证件正面上传失败,请重新上传'))
        return
      }
      if (!this.isLoad2) {
        this.$toast(this.$t('证件反面上传失败,请重新上传'))
        return
      }
      if (!this.isLoad3 ) {
        this.$toast(this.$t('手持证件上传失败,请重新上传'))
        return
      }
      _loanApply({
        ...this.loanData,
        // term:this.loanData.term,
        quota: this.loanAmount,//借贷金额 改输入
        // dailyRate: this.loanData.dailyRate,
        // lendingInstitution:this.loanData.lendingInstitution,//放款机构名字
        // lendingName:this.loanData.lendingName,
        // repayment:this.loanData.repayment,//还款方式
        // repayCycle:this.loanData.repayCycle, //还款日期
        symbol: 'USDT',
        frontFile: this.frontFile[0].resURL,
        reverseFile: this.reverseFile[0].resURL,
        fileList: this.fileList[0].resURL,
      }).then(res => {
        // console.log('res',res)
        this.$router.push('/loanHistory')
      }).catch(err => {
        this.$toast(this.$t(err.msg))
      })
    },
    //防抖
    inputAmunt(){
      this.loanAmount = this.loanAmount.replace(/[^0-9]/g, '')
      this.debounceFn()
    },
    debounceFn: debounce(function () {
      this.getInterest()
    }, 500),
    getInterest(){
      if(+this.loanAmount > +this.loanData.maxQuota){
        this.$toast(this.$t('最大可借:') + this.loanData.maxQuota)
        this.loanAmount = 0
        return 0
      }
      let num =  this.$bigDecimal.multiply(+this.loanAmount, +this.loanData.dailyRate) * +this.loanData.term || 0
      return num.toFixed(2)
    },
    selectDay(data) {
      this.loanData = data
      this.loanAmount= this.loanData.minQuota
      this.isSelectDay = false
    },
/*    onClickUpload(type) {
      this.curFile = type
    },*/
    afterRead(file,type) { /// 处理文件
      // console.log(file)
      file.status = 'uploading'
      file.message = this.$t('上传中...')
      _uploadImage(file).then(data => {
        file.status = 'success';
        file.message = this.$t('上传成功');
        file.resURL = data
        this[type] = [file]
        if(type === 'frontFile'){
          this.isLoad1 = true
        }else if(type === 'reverseFile'){
          this.isLoad2 = true
        }else{
          this.isLoad3 = true
        }
      }).catch(err => {
        file.status = 'failed';
        file.message = this.$t('图片上传失败');
      })
    },
  },
  mounted() {
    this.getLoan()
    if (!this.userInfo.token) {
      this.$router.push('/login')
    }
  },
  data() {
    return {
      loanData: {},
      loanDeployList: [],
      frontFile: [],
      reverseFile: [],
      fileList: [],
      curFile: 'frontFile',
      // resultArr: ['small-success_' + this.$t('已申请未审核'), 'identifing_' + this.$t('审核中'), 'small-success_' + this.$t('审核通过'), 'icon-close_' + this.$t('审核未通过')], // 0 好像是未提交
      // status:'',
      isSelectDay: false,
      isUpload: false,
      loanAmount:0,//输入的借款金额
      isLoad1:false,
      isLoad2:false,
      isLoad3:false,
    }
  }
}
</script>

<style scoped lang="scss">
.loan {
  width: 100%;
  box-sizing: border-box;
}

.uploadImg {
  margin-top: 60px;

  .upload-wrap {
    width: 356px;
    height: 288px;
    display: flex;
    justify-content: center;
    align-items: center;

    ::v-deep .van-uploader__upload {
      width: 356px !important;
      height: 288px !important;
    }
  }
}

.selectDay {
  position: absolute;
  left: -70px;
  background: #f5f5f5;
  color: #333;
  box-sizing: border-box;

  div {
    padding: 20px 70px;
  }

  div:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.confirmBtn {
  border-radius: 8px;
}

.grayText {
  color: #868E9B;
}</style>